<script lang="ts" setup>
import type { VxeGridProps, VxePagerEvents } from 'vxe-table'

import { couponDataList, couponDataPage, couponEnable, getBusinessBlocksList } from '@fl/api/anjutong'
import { SearchForm, SearchTable } from '@fl/components'
import { cloneDeep } from 'lodash-es'
import { useRouter } from 'vue-router'

import activityData from '../components/activity-data.vue'
import { couponInfo } from './type'

const router = useRouter()

const initialState = {
    companyName: '', // 项目名称
    couponName: '', // 券名称
    couponType: 2, // 券类型（1-优惠券 2-折扣券）
    enableStatus: undefined, // 启用状态（1：启用 0:禁用）
    plate: undefined, // 业务块ID
}
const businessModulesList = ref([])
const plate = ref()
const state = ref(cloneDeep(initialState))
const columns = ref([
    {
        label: '折扣劵名称',
        prop: 'couponName',
        valueType: 'copy',
    },
    {
        label: '项目名称',
        prop: 'projectName',
        valueType: 'copy',
    },
    {
        fieldProps: {
            filterable: true,
            props: {
                emitPath: false,
                label: 'name',
                value: 'code',
            },
        },
        label: '业务板块',
        options: [],
        prop: 'plate',
        valueType: 'cascader',
    },
    {
        label: '状态',
        options: [
            {
                label: '进行中',
                value: 1,
            },
            {
                label: '已结束',
                value: 0,
            },
        ],
        prop: 'enableStatus',
        valueType: 'select',
    },
])
const initialPage = {
    currentPage: 1,
    pageSize: 10,
    total: 0,
}
const tablePage = ref(cloneDeep(initialPage))
const gridOptions = reactive<VxeGridProps>({
    columns: [
        { title: '序号', type: 'seq', width: 70 },
        { field: 'couponName', minWidth: 200, title: '折扣券名称' },
        { field: 'projectNames', minWidth: 260, title: '项目名称' },
        { field: 'plateName', minWidth: 100, title: '业务板块' },
        { field: 'status', minWidth: 120, slots: { default: 'status' }, title: '状态' },
        { field: 'enableStatus', minWidth: 90, slots: { default: 'enableStatus' }, title: '启用/停用' },
        { field: 'time', minWidth: 300, slots: { default: 'time' }, title: '有效期' },
        { fixed: 'right', minWidth: 210, slots: { default: 'operate' }, title: '操作' },
    ],
})
const list = ref([])
const isLoading = ref(false)
const dialogVisible = ref(false)
const couponId = ref()

init()

/**
 * methods start
 */

function init() {
    getDiscountList()
    getBusinessModules()
}

// 获取板块列表
function getBusinessModules() {
    getBusinessBlocksList().then((res) => {
        businessModulesList.value = res
    })
}

// 获取折扣劵列表
function getDiscountList() {
    couponDataPage({
        ...state.value,
        couponType: 2, // 1优惠券 2折扣劵
        pageNum: tablePage.value.currentPage,
        pageSize: tablePage.value.pageSize,
        plate: plate.value,

    }).then((res) => {
        list.value = res.records
        tablePage.value.total = res.total
    })
}

function resetSearch() {
    state.value = cloneDeep(initialState)
    plate.value = undefined
    getDiscountList()
}

function submitSearch(values) {
    state.value = values
    tablePage.value.currentPage = 1
    getDiscountList()
}

function showData(row) {
    couponId.value = row.id
    dialogVisible.value = true
}

const handlePageChange: VxePagerEvents.PageChange = ({ currentPage, pageSize }) => {
    tablePage.value.currentPage = currentPage
    tablePage.value.pageSize = pageSize
    getDiscountList()
}

// 跳转详情（新增、编辑）页面
function toPage(name, type, row) {
    const id = type === 'add' ? 'item' : row.id
    router.push({ name, params: { id, type } })
}

// 启用/禁用优惠券
function setStatus(row) {
    couponEnable({ id: row.id }).then(() => {
        ElMessage.success('操作成功')
        getDiscountList()
    })
}
/**
 * methods end
 */
</script>

<template>
    <div class="activity-coupon-manage">
        <ElCard class="mb-20"
                shadow="never"
        >
            <SearchForm v-bind="state"
                        :columns="columns"
                        submit-text="搜索"
                        @reset="resetSearch"
                        @submit="submitSearch"
            >
                <template #plus-field-plate>
                    <el-select v-model="plate">
                        <el-option v-for="item in businessModulesList"
                                   :key="item.value"
                                   :label="item.label"
                                   :value="item.value"
                                   :disabled="item.disabled"
                        />
                    </el-select>
                </template>
            </SearchForm>
        </ElCard>

        <ElCard shadow="never">
            <SearchTable v-bind="gridOptions"
                         v-model:pager="tablePage"
                         :loading="isLoading"
                         :data="list"
                         @page-change="handlePageChange"
            >
                <template #toolbar_buttons>
                    <el-button plain
                               type="primary"
                               @click="toPage('discount-manage-detail', 'add')"
                    >
                        新增
                    </el-button>
                </template>

                <template #time="{ row }">
                    {{ row.startTime }} ~ {{ row.endTime }}
                </template>

                <template #status="{ row }">
                    {{ ['已结束', '进行中'][row.enableStatus] }}
                </template>

                <template #enableStatus="{ row }">
                    <el-switch v-model="row.enableStatus"
                               :active-value="1"
                               :inactive-value="0"
                               @change="setStatus(row)"
                    />
                </template>

                <template #operate="{ row }">
                    <div class="operate-btns">
                        <el-button type="primary"
                                   text
                                   @click="toPage('discount-manage-detail', 'copy', row)"
                        >
                            复制
                        </el-button>

                        <el-button type="primary"
                                   text
                                   @click="showData(row)"
                        >
                            数据
                        </el-button>

                        <el-button type="primary"
                                   text
                                   @click="toPage('discount-manage-detail', 'edit', row)"
                        >
                            编辑
                        </el-button>
                    </div>
                </template>
            </SearchTable>
        </ElCard>

        <el-dialog v-model="dialogVisible"
                   :close-on-click-modal="false"
                   :close-on-press-escape="false"
                   title="折扣劵领取/使用情况"
                   width="1062"
                   modal-class="coupon-data-dialog"
                   draggable
        >
            <activityData :id="couponId"
                          name="discount"
            />
        </el-dialog>
    </div>
</template>

<style lang="scss" scoped>
.coupon-data-dialog {
}
:deep(.coupon-data-dialog .el-dialog) {
    height: calc(100vh - 120px) !important;
}
:deep(.coupon-data-dialog .el-dialog__body) {
    overflow: hidden;
    overflow-y: auto;
}
:deep(.operate-btns .el-button) {
    margin: 0;
    padding: 6px;
}
</style>
